<?php

namespace MSDK\Model;

/**
 * Description of UserModel
 *
 * @author Su 2015-3-5
 */
class MSDKAdminModel extends AppbaseModel {

    protected $tableName = 'tuser_member';
// 命名范围
    protected $_scope = array(
// login
        'login' => array(
            'field' => 'id, userName, extensionNumber, password, userType, state, siteID, allowOverdraftAmount, teamNumber, ctiTrunk, ctiCallerNo',
        ),
        'idtext' => array(
            'field' => array('siteID as id', "concat(userName,'[',siteID,']') as text"),
            'where' => array('userType' => 'ADMIN'),
            'cache' => true,
        ),
        'export' => array(
            'field' => "siteID as '租户ID', userName as '用户名', outFeeRate as '呼出费率', inFeeRate as '呼入费率', smsFeeRate as '短信费率',  blance as '余额', allowOverdraftAmount as '可透支金额', payType as '付费方式'",
            'where' => "userType='ADMIN'",
            'order' => 'siteID',
            'cache' => 15,
        ),
        'item_list' => array(
            'field' => 'id,siteID,userName,maxTask,outFeeRate,inFeeRate,smsFeeRate,blance,allowOverdraftAmount,payType,role_id,state,createdTime',
            'order' => 'createdTime desc',
            'cache' => 15,
        ),
    );
    protected $_auto = array(
        array('state', 1, self::MODEL_INSERT),
        array('userType', 'ADMIN', self::MODEL_BOTH),
    );
    protected $patchValidate = true;

    public function scope_fields($scope = 'idtext') {
        return $this->base_get_scope_fields($scope);
    }

    /**
     * 修改密码
     * @param string|array $where 查询条件
     * @param string $pwd 新密码
     * @return false|int 成功则返回受影响数量,失败返回false
     * @since 1.0 2015-3-6 by sutroon
     */
    public function update_password($where, $pwd) {
        $result = $M->where($where)->setField('password', $pwd);
        $condition = is_array($where) ? sofunc_array_implode(',', $where) : $where;
        BaseModel::add_user_event_log('密码', "[修改%] $condition, password=$pwd", $result);
        return $result;
    }

    /**
     * 保存管理员
     * @param int $admin_id 管理员编号
     * @return array
     * @since 1.0 2015-3-6 by sutroon
     */
    public function save_admin($admin_id) {
        $validator = array(
            array('userName', 'require', '用户名无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('userName', 'require', '用户名已被注册!', self::MUST_VALIDATE, 'unique', self::MODEL_INSERT),
            array('siteID', 'number', '租户ID必须选择!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('siteID', 'number', '租户ID已被使用!', self::MUST_VALIDATE, 'unique', self::MODEL_INSERT),
            array('password', 'require', '密码无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('maxTask', 'number', '任务最大数量无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('keepCallHistoryDays', 'require', '通话清单最大保留时间必须选择!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('keepRecordHistoryDays', 'require', '录音最大保留时间必须选择!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('outFeeRate', 'require', '呼出使用费率必须选择!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('inFeeRate', 'require', '呼入使用费率必须选择!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('smsFeeRate', 'require', '短信使用费率必须选择!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('allowOverdraftAmount', 'double', '可透支金额无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('payType', 'number', '付费类型有误!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('state', 'number', '状态有误!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        $is_edit = I('id') ? true : false;
        if (!$this->validate($validator)->create()) {
            D('Log')->log_user_operate(false, sprintf('%s管理员账户失败 user=%s, siteID=%d %s', ($is_edit ? '编辑' : '新增'), $this->data['userName'], $this->data['siteID'], implode('; ', $this->getError())), $admin_id, ($is_edit ? LogModel::ACTION_EDIT : LogModel::ACTION_ADD));
            return $this->returnMsg(false, $this->getError());
        }
        $data = $this->data;
        if ($is_edit) {
            $result = $this->save();
            if (false !== $result) {
                $this->table('tcti_daybill')->where(array('billdate' => date('Y-m-d'), 'siteID' => $data['siteID']))->setField('allowOverdraftAmount', $data['allowOverdraftAmount']);
            }
        } else {
            $this->data['createdTime'] = date('Y-m-d H:i:s');
            $this->data['role_id'] = 2;
            $result = $this->add();
            if (false !== $result) {
                if ('TTF' == C('USER.USER_KEY')) { // 台湾版需创建客资表
                    D('DbTable')->create_table('CALL_NUMBER', sofn_get_sharding_field('DB_SERVICE') . 'tcustomer_' . $data['siteID']);
                }
                D('DbTable')->create_table('CALL_NUMBER', sofn_get_sharding_field('DB_IMPORT_TEMP') . 'tcall_number_temp_' . $data['siteID'], array('ENGINEE' => 'Memory'));
                D('DbTable')->create_table('CDR', sofn_get_sharding_field('DB_CDR_HISTORY') . 'cdr_' . $data['siteID']);
                $this->execute('insert into tuser_appsetting (userID, pageSize) values (' . $result . ',' . C('USER.PAGE_SIZE') . ')');
                $this->execute('insert into tcti_workday (weekday,siteID,createdTime) values ("1,2,3,4,5",' . $data['siteID'] . ',"' . date('Y-m-d H:i:s') . '");');
            }
        }
        D('Log')->log_user_operate($result, sprintf('%s管理员账户%s user=%s, siteID=%d', ($is_edit ? '编辑' : '新增'), '{%}', $data['userName'], $data['siteID']), $admin_id, ($is_edit ? LogModel::ACTION_EDIT : LogModel::ACTION_ADD));
        return $this->returnMsg($result);
    }

    /**
     * 删除管理员
     * @param string $id 主键编号,多个之间以逗号隔开
     * @param int $admin_id 操作员编号
     * @return array
     * @since 1.0 <2015-6-10> SoChishun Added.
     */
    public function admin_delete($id, $admin_id) {
        if (!$admin_id) {
            return $this->returnMsg(false, '管理员无效');
        }
        if (!$id) {
            return $this->returnMsg(false, '编号无效');
        }
        $status = false;
        $errs = array();
        $aids = explode(',', $id);
        foreach ($aids as $sid) {
            $result = $this->query("select func_delete_admin($sid)");
            $code = current($result[0]);
            if (1 == $code) {
                $status = true;
            }
            if (1 < $code) {
                $errs[] = '租户[' . $sid . '] ' . sofn_get_procedure_result_text($code, array(4301 => '分机未清理', 4302 => '队列未清理', 4303 => '中继未清理', 4304 => '语音未清理', 4305 => '语音菜单未清理', 4306 => '策略未清理', 4307 => '自动登录未清理', 4308 => '来话导航未清理'));
            }
        }
        $msg = implode(',' . PHP_EOL, $errs);
        D('Log')->log_user_operate($status, "删除管理员账户($id){%} $msg,操作员:$admin_id", $admin_id, LogModel::ACTION_DELETE);
        $this->clear_table_caching(array('tuser_member', 'tcti_acd_queue', 'tcti_trunk', 'tgeneral_file', 'tcti_voice_menu', 'tcti_task_strategy', 'tcti_income_nav', 'tcti_daybill', 'tcti_meeting_room', 'tcti_workday', 'tfinance_recharge'));
        return $this->returnMsg($status, $msg);
    }

    /**
     * 返回列表
     * @return array
     * @xince 1.0 <2015-6-9> SoChishun Added.
     */
    public function get_admin_list($where) {
        for ($i = 1; $i < 25; $i++) {
            $out[] = array('id' => $i, 'user_name' => 'user ' . $i, 'role_id' => 1, 'role_text' => '管理员', 'state' => 1, 'state_text' => '正常', 'create_time' => '2015-09-11 17:56:30');
        }
        $total = 100;
        return array('total' => $total, 'rows' => $out);
    }

}
